<template>
  <section class="content">
    <details-head v-model="status"
                  :title="`数量拆单`"
                  :custom-list="buttonList"
                  :multiple="true"
                  :loading="loading"
                  closeLabel="返回"
                  @change="save" />
    <div class="body">
      <div class="titleSty">被拆运单</div>
      <dispatch-order :records-list="recordsList"></dispatch-order>
      <div class="mt45">
        <span class="flex-start">
          <div class="titleSty">数量拆分过程</div>
          <el-button class="ml20"
                     :disabled="goodsList.length > 0 && goodsList[0].order.length > 9"
                     :type="goodsList.length > 0 && goodsList[0].order.length > 9 ? 'info':'primary'"
                     @click="handleAdd">新增单数</el-button>
        </span>
        <num-process ref="process"
                     :goods-list="goodsList"
                     @handleDispatchDetails="handleDispatchDetails"></num-process>
      </div>
      <div class="mt45">
        <div class="titleSty">预览</div>
        <dispatch-details :process-list="processList"></dispatch-details>
      </div>
    </div>
  </section>
</template>

<script>
import DetailsHead from "@components/detailsHead/Header.vue";
import NumProcess from "./components/NumProcess.vue";
import DispatchOrder from "./components/DispatchOrder.vue";
import DispatchDetails from "./components/DispatchDetails.vue";
import { transport, splitting } from "@/api/index";
import { returnThousandDigit } from "@/libs/util.js";
export default {
  name: "NumSplitting",
  components: {
    DetailsHead,
    DispatchOrder,
    NumProcess,
    DispatchDetails
  },
  data () {
    return {
      loading: false,
      status: "1",
      buttonList: [{ label: "确定拆单", status: "1" }],
      recordsList: [],
      goodsList: [],
      processList: []
    };
  },
  computed: {
    waybillId () {
      return this.$route.query?.waybillId || this.$route.query?.id;
    }
  },
  created () {
    this.getTransportDetail();
  },
  methods: {
    async getTransportDetail () {
      let { code, data } = await transport.getDetail(this.waybillId);
      if (code !== 0) return;
      if (data && data.goodsList) {
        data.goodsList.map((item) => {
          this.goodsList.push({
            ...item,
            order: [
              {
                num: item.quantity,
                goodsName: item.goodsName,
                spec: item.spec,
                quantity: item.quantity,
                volume: item.volume,
                weight: item.weight
              },
              {
                num: null,
                goodsName: item.goodsName,
                spec: item.spec,
                quantity: item.quantity,
                volume: item.volume,
                weight: item.weight
              }
            ]
          });
        });
      }
      this.recordsList.push({
        no: data.contractNo,
        from: {
          cstName: data.customer.customerName,
          address: `${data.fromAddress.province}${data.fromAddress.city}${data.fromAddress.district}${data.fromAddress.address}`,
          customer: data.fromContact.contactName,
          tel: data.fromContact.contactMobile,
          time: data.fromTime
        },
        to: {
          cstName: data.consignee.consigneeName,
          address: `${data.toAddress.province}${data.toAddress.city}${data.toAddress.district}${data.toAddress.address}`,
          customer: data.toContact.contactName,
          tel: data.toContact.contactMobile,
          time: data.toTime
        },
        num: returnThousandDigit(data.waybillCache.totalQuantity),
        volumn: returnThousandDigit(data.waybillCache.calculateVolume, 2),
        weight: returnThousandDigit(data.waybillCache.calculateWeight, 2)
      });
    },
    // 新增单数
    handleAdd () {
      if (this.goodsList[0].order.length < 10) {
        this.goodsList.map((item) => {
          item.order.push({
            num: null,
            goodsName: item.goodsName,
            spec: item.spec,
            quantity: item.quantity,
            volume: item.volume,
            weight: item.weight
          });
        });
      } else {
        this.$message.error("最多可拆分10段");
      }
    },
    handleDispatchDetails (list) {
      this.goodsList = [...list];
      let maxLength = 0;
      let arr = [];
      let data = [];
      this.goodsList.map((item) => {
        maxLength =
          item.order.length > maxLength ? item.order.length : maxLength;
        arr.push(item.order);
      });
      for (let i = 0; i < maxLength; i++) {
        let sum = 0,
          vSum = 0,
          wSum = 0;
        let info = [];
        arr.map((item) => {
          if (item[i] && item[i].num) {
            sum += Number(item[i].num);
            vSum += Number(item[i].num) * item[i].volume;
            wSum += Number(item[i].num) * item[i].weight;
          }
          info.push({
            goodsName: item[i].goodsName,
            spec: item[i].spec,
            num: item[i].num
          });
        });
        data.push({
          childNum: sum,
          childVolumn: returnThousandDigit(vSum, 2),
          childWeight: returnThousandDigit(wSum, 2),
          info
        });
      }
      this.processList = data;
    },
    // 触发事件
    save () {
      let errorFlag = false;
      try {
        this.goodsList.forEach(function (item) {
          if (item.flag) {
            errorFlag = item.flag;
            throw Error();
          }
        });
      } catch (e) {
        console.log("err", "拆分的运单，数量填写有误")
      }
      if (errorFlag) return false;
      let numFlag = this.processList.length < 1 || this.processList.length != this.goodsList[0].order.length ? true : false;
      try {
        this.processList.forEach(function (item) {
          if (item.childNum === 0 || !item.childNum) {
            numFlag = true;
            throw Error();
          }
        });
      } catch (e) {
        console.log("err", "拆分的运单，总数量不能为0")
      }
      if (numFlag) {
        return this.$message.error("拆分的运单，总数量不能为0");
      }
      this.loading = true;
      this.numSplit();
    },
    // 拆单
    async numSplit () {
      let arr = [];
      let totalNumFlag = false;
      this.goodsList.map((item) => {
        let totalNum = 0;   //每个物品填写值的总和
        let numArr = [];
        item.order.map((option) => {
          totalNum += Number(option.num)
          numArr.push(Number(option.num));
        });
        item.totalNum = totalNum;
        if (item.totalNum != item.quantity) {
          totalNumFlag = true
        }
        arr.push({ waybillGoodsId: item.waybillGoodsId, goodsNums: numArr });
      });
      if (totalNumFlag) {
        this.loading = false;
        return this.$message.warning("物品数量合计不能大于或是小于总数量");
      }
      const _this = this;
      let { code } = await splitting.split({
        waybillId: this.waybillId,
        waybillDivideMode: 2,
        spec: { goodsNumList: arr }
      }).catch(() => {
        this.loading = false;
      })
      if (code === 0) {
        this.$message.success("拆单成功！");
        this.loading = false;
        if (this.$route.query.detailFlag) {
          _this.$router.go(-2);
        } else {
          _this.$router.back();
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  background: var(--prev-bg-white);
  padding: 20px;
  position: relative;
  height: 88vh;
}
.body {
  height: 80vh;
  overflow-x: hidden;
  margin-top: 20px;
}
.footer {
  position: absolute;
  top: 89%;
  left: 0;
  background-color: var(--prev-bg-white);
  width: 100%;
  height: 9vh;
  margin-top: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 3px solid var(--prev-bg-lightgrey);
}
.flex-start {
  display: flex;
  align-items: flex-start;
}
.titleSty {
  // width: 200px;
  height: 16px;
  border-left: 2px solid var(--prev-color-primary);
  padding-left: 6px;
  margin-bottom: 30px;
  font-size: 16px;
  font-weight: 500;
  margin-top: 5px;
}
.mt45 {
  margin-top: 45px;
}
.ml20 {
  margin-left: 20px;
}
/deep/ .el-input__inner {
  border: hidden !important;
}
</style>
